<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mindex extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    public $default= array(
        array('id'=>1,'url'=>'google.com.vn','image'=>'images/slides/8412ef8cb970c688a9d887d845a56229.jpg'),
        array('id'=>2,'url'=>'24.com.vn','image'=>'images/slides/028ccc9a63febdcbcf451a41c086eb8a.jpg'),
    );
    public function getRestaurantLabelDb($time)
    {
        $timeupdate = $this->db->query("SELECT content FROM options WHERE tags = 'time_update_restaurant'")->row_object();
        if($time < $timeupdate->content)
        {
            $sql = "SELECT id,orderby,name,image,logo,share_facebook_url,hotline,phone_hotline FROM restaurant ORDER BY orderby ASC";
            $data = $this->db->query($sql)->result_array();
            
            $arr = array();
            foreach($data AS $item)
            {
                $sql_zone = "SELECT id,title FROM zone ORDER BY id ASC";
                $zone = $this->db->query($sql_zone)->result_array();
                $arr_zone = array();
                foreach($zone AS $itemz)
                {
                    $sql_address = "SELECT ra.id,ra.address,ra.phone,ra.latitude,ra.longitude FROM restaurant_address AS ra LEFT JOIN zone AS z ON z.id = ra.id_zone WHERE ra.restaurant_id = ".$item['id']." AND z.id = ".$itemz['id']." ORDER BY ra.id ASC";
                    $address = $this->db->query($sql_address)->result_array();
                    if(!in_array($address, array(null, '', '0', 0))){
                        $itemz['list'] = $address;
                        $arr_zone[] = $itemz;
                    }
                }
                $item['address'] = $arr_zone;
                
                $arr['id_'.$item['id']] = $item;
            }
            
            $arr['time_update'] = $timeupdate->content;
            return (object)array('status' => 200, 'data' => (array)$arr);
        }else{
            return (object)array('status' => 201, 'data' => '');
        }
    }
    
    /**
     * Get All Slide
     * 
     * @param int $time
     * @return object
     */
    public function getStaticDataDb($time)
    {
        $timeupdate = $this->db->query("SELECT content FROM options WHERE tags = 'time_update_api_static'")->row_object();
//        var_dump($timeupdate->content);die;
        if($time < $timeupdate->content)
        {
            $slides = $this->db->query("SELECT * FROM slide")->result_array();
//            var_dump($slides);die;           
            $arr = array(
                  'slides' => $slides,
            );
            return (object)array('status' => 200, 'data' => (object)$arr);
        }else{
            return (object)array('status' => 201, 'data' => '');
        }
    }
    
    /**
     * Get Slide with zone .
     * 
     * @param int $time
     * @param int $zone
     * @return object
     */
    public function getSlideZoneDb($zone)
    {
//        $timeupdate = $this->db->query("SELECT content FROM options WHERE tags = 'time_update_api_static'")->row_object();
//        var_dump($timeupdate->content);die;
        $checkZone=$this->db->query("SELECT id FROM zone WHERE id = $zone")->num_rows;
        if($checkZone==0){
            return (object)array('status' => 202,'description'=>'Không thấy zone','default_image'=>$this->default);//Không tìm thấy zone
        }
        
//        if($time < $timeupdate->content)
//        {
            $slides = $this->db->query("SELECT slide.* FROM slide,slide_zone Where slide.id=slide_zone.slide_id AND slide_zone.zone_id = $zone")->result_array();
            if(count($slides)==0) 
            {
               return (object)array('status' => 201,'description'=>'Không thấy slide','default_image'=>$this->default);  //với zone đã tìm ko tim thay slide
            }
            $arr = array(
                  'slides' => $slides,
            );
            return (object)array('status' => 200,'description'=>'Tìm thấy slide', 'data' => (object)$arr);   //tìm thấy slie 
//        }else{
//            return (object)array('status' => 202, 'data' => '');
//        }
    }
    
    /**
     * Get All slide
     * 
     * @param int $time
     * @param int $zone
     * @return object
     */
    public function getAllSlideDb()
    {
        $slides = $this->db->query("SELECT slide.*,zone.id as id_zone,zone.title as title_zone FROM slide,slide_zone,zone Where slide.id=slide_zone.slide_id AND slide_zone.zone_id=zone.id")->result_array();
        if(count($slides)==0) 
        {
            return (object) array('status' => 201, 'description' => 'Không thấy slide', 'default_image' => $this->default);  //với zone đã tìm ko tim thay slide
        }
        $arr = array(
            'slides' => $slides,
            'default_image'=> $default
        );
        return (object)array('status' => 200,'description'=>'Tìm thấy slide', 'data' => (object)$arr); 
    }
    
    public function getProvinceDb()
    {
        $province = $this->db->query("SELECT * FROM vn_province ORDER BY provinceid ASC")->result_array();
        
        $data = array();
        foreach($province AS $key => $val){
            $district = $this->db->query("SELECT districtid,name,type,provinceid FROM vn_district WHERE provinceid = ".$val['provinceid'])->result_array();
            $val['district'] = $district;
            $data[] = $val;
        }
        
        return $data;
    }
    
    public function getRestaurantDetailDb($restaurant_id,$user_id)
    {       
        $sql = "SELECT id,name,image,logo,share_facebook_url,hotline,phone_hotline,restaurant_like as number_like FROM restaurant WHERE id = ".$restaurant_id." ORDER BY orderby ASC";
        $result= $this->db->query($sql);
        if($result->num_rows()== 0) return (object)array('status' => 201, 'data' => (array)$data,'description'=>'Không tìm thấy nhà hàng');
        $data=$result->row_array();
//        $data = $this->db->query($sql)->row_array();
//        if($data-> )
        $sql_zone = "SELECT id,title FROM zone ORDER BY id ASC";
//        $sql_zone = "SELECT id,title FROM zone WHERE id = $zone ORDER BY id ASC";
        $zone = $this->db->query($sql_zone)->result_array();
        $arr_zone = array();
        foreach($zone AS $item)
        {
            $sql_address = "SELECT ra.id,ra.address,ra.phone,ra.latitude,ra.longitude FROM restaurant_address AS ra LEFT JOIN zone AS z ON z.id = ra.id_zone WHERE ra.restaurant_id = ".$data['id']." AND z.id = ".$item['id']." ORDER BY ra.id ASC";
            $address = $this->db->query($sql_address)->result_array();
            //var_dump($this->db->last_query());die;
            if(!in_array($address, array(null, '', '0', 0))){
                $item['list'] = $address;
                $arr_zone[] = $item;
            }
        }
        $data['address'] = $arr_zone;
        //CHeck like
        if($user_id != null)
        {
            $checkUser=$this->db->query("SELECT * FROM member WHERE id = '$user_id'")->num_rows();
            if($checkUser == 0) return (object)array('status' => 201,'description'=>'Không tìm user');
            $check=$this->db->query("SELECT * FROM restaurant_user WHERE restaurant_id='$restaurant_id' AND user_id='$user_id' ")->num_rows();
            $data['check_like'] = $check;
        }
        else
        {
           $data['check_like']=0; 
        }  
        $data['name']=  stripslashes(stripslashes($data['name']));
		$menus = $this->db->query('SELECT id, name FROM restaurant_menus_categories WHERE restaurant_id = '.$restaurant_id.' ORDER BY orderby ASC ')->result_object();
		foreach ( $menus AS $el=>$le ){
			$menus[$el]->food = $this->db->query('SELECT id, name, price, FORMAT(price,0) AS prices, summary, CONCAT("http://125.212.192.114/wicard/data/", image) AS image  FROM restaurant_menus_food WHERE categories_id = '.$le->id.' ORDER BY orderby ASC ')->result_object();
		}
		$data['menus'] = $menus;
        return (object)array('status' => 200, 'data' => (array)$data,'description'=>'Tìm thấy chi tiết');
    }
	
    public function getIncentiveDetail($id){
            return $this->db->query('SELECT * FROM incentive_restaurant WHERE id = '.$id.' LIMIT 1')->row_object();
    }
	
//    public function getNearRestaurant($restaurantid,$zone)
//    {
//                //Lấy thông tin restaurant(id,name,logo)
//		if( !in_array( $restaurantid,array('',null) ) ){
//			$sql = "SELECT id,name AS restaurantname,logo FROM restaurant WHERE id = ".$restaurantid;
//		}else{
//			$sql = "SELECT id,name AS restaurantname,logo FROM restaurant ORDER BY orderby ASC";
//		}
//		$data = $this->db->query($sql)->result_object();
////                var_dump($data);die;
//		//echo '<pre>';die(print_r($data));
//		$arr = array();
//                //Lấy restaurant address id,address,phone,latitude,longtitude.
//		foreach($data AS $el=>$le)
//		{
//			if( !in_array( $locationid,array('',null) ) ){
//				$sql_address = "SELECT ra.id,ra.address,ra.phone,ra.latitude,ra.longitude FROM restaurant_address AS ra WHERE ra.restaurant_id = ".$le->id." AND ra.id = ".$locationid." ORDER BY ra.id ASC";
//			}else{
//				$sql_address = "SELECT ra.id,ra.address,ra.phone,ra.latitude,ra.longitude FROM restaurant_address AS ra WHERE ra.restaurant_id = ".$le->id." ORDER BY ra.id ASC";
//			}
//			$address = $this->db->query($sql_address)->result_object();
//			foreach ( $address AS $il=>$li ){
//				$address[$il]->restaurantid = $le->id;
//				$address[$il]->logo = $le->logo;
//				$address[$il]->restaurantname = $le->restaurantname;
//			}
//			$data[$el]->address = $address;
//			$arr = array_merge($arr, $address);
//		}
//		return ($arr);
//    }
    
//    public function getNearRestaurant($restaurant_name,$zone)
//    {   
//        //check zone 
//        $countZone=$this->db->query("SELECT * FROM zone WHERE zone.id =$zone")->num_rows();
//        if(in_array( $zone,array('',null,'0') ) || $countZone == 0)
//        {
//            return (object)array('status' => 202, 'description' => 'Zone không tồn tại');
//        }
////        var_dump($restaurant_name,$zone);die;
//        //Check restaurant id
//        //Nếu restaurant là null thì ko lọc theo restaurant_name còn ko thì thôi
////        var_dump(in_array('a',array('','0') ));die;
//        if(in_array( $restaurant_name,array('',null,'0') ))
//        {
//            $query = " SELECT ra.id as id_address,ra.address,ra.phone,ra.latitude,ra.longitude ,r.name,r.logo,r.id as id_restaurant "
//                . "FROM restaurant as r,restaurant_address as ra WHERE r.id=ra.restaurant_id "
//                . "AND ra.id_zone=$zone order by ra.id";
//        }
//        else {
//            $query= " SELECT ra.id as id_address,ra.address,ra.phone,ra.latitude,ra.longitude ,r.name,r.logo,r.id as id_restaurant "
//                . "FROM restaurant as r,restaurant_address as ra WHERE r.id=ra.restaurant_id "
//                . " AND r.name_ascii LIKE '%$restaurant_name%' AND ra.id_zone=$zone order by ra.id ";
////            var_dump($query);die;
//        }
//        $res=$this->db->query($query);
//        $countRes=$res->num_rows();
//        $arrRes=$res->result_array();
//        if($countRes == 0)return (object)array('status' => 201, 'description' => 'Không tìm thấy kết quả'); 
//        return (object)array('status' => 200, 'description' => 'Tìm thấy','data'=>$arrRes); 
//    }
    
    public function getNearRestaurant($restaurantid,$zone)
    {   
        //check zone 
        $countZone=$this->db->query("SELECT * FROM zone WHERE zone.id =$zone")->num_rows();
        if(in_array( $zone,array('',null) ) || $countZone == 0)
        {
            return (object)array('status' => 202, 'description' => 'Zone không tồn tại');
        }
        
        //Check restaurant id
        //Nếu restaurant là null thì ko lọc theo restaurant id còn ko thì thôi
        if(in_array( $restaurantid,array('',null) ))
        {
           
            $query =  " SELECT ra.id as id_address,ra.address,ra.phone,ra.latitude,ra.longitude ,r.name,r.logo,r.id as id_restaurant "
                . "FROM restaurant as r,restaurant_address as ra WHERE r.id=ra.restaurant_id "
                . "AND ra.id_zone=$zone order by ra.id";
        }
        else {
            $query=  " SELECT ra.id as id_address,ra.address,ra.phone,ra.latitude,ra.longitude ,r.name,r.logo,r.id as id_restaurant "
                . "FROM restaurant as r,restaurant_address as ra WHERE r.id=ra.restaurant_id "
                . " AND r.id =$restaurantid AND ra.id_zone=$zone order by ra.id ";
        }
        $res=$this->db->query($query);
        $countRes=$res->num_rows();
        $arrRes=$res->result_array();
        foreach ($arrRes as $key => $value)
        {
                $arrRes[$key]['name']=  stripslashes(stripslashes($value['name']));
        }
        if($countRes == 0)return (object)array('status' => 201, 'description' => 'Không tìm thấy kết quả'); 
        return (object)array('status' => 200, 'description' => 'Tìm thấy','data'=>$arrRes); 
    }
    
    public function addLikeRestaurantDb( $restaurant_id,$user_id){
        //check restauran id
        if($this->db->query('SELECT id from member WHERE id = '.$user_id)->num_rows()== 0){
           return (object)array('status' => 202, 'description' => 'User không tồn tại');
        }
        //check user id
        if($this->db->query('SELECT id from restaurant WHERE id = '.$restaurant_id)->num_rows()== 0){
           return (object)array('status' => 202, 'description' => 'Restaurant không tồn tại'); 
        }
        //check like 1 lan /1 user
        if($this->db->query('SELECT id from restaurant_user WHERE restaurant_id = '.$restaurant_id.' AND user_id = '.$user_id)->num_rows()!= 0){
           $this->db->query('DELETE FROM restaurant_user WHERE restaurant_id = '.$restaurant_id.' AND user_id = '.$user_id);
           $this->db->query("UPDATE restaurant SET restaurant_like = restaurant_like - 1 WHERE id = $restaurant_id"); 
           $total_like=$this->db->query("SELECT restaurant_like FROM restaurant WHERE id = '$restaurant_id'")->row()->restaurant_like; 
           return (object)array('status' => 203, 'description' => 'Đã hủy like ','total_like'=>$total_like);
             
        }
        //add like 
        $data = array('user_id' =>$user_id ,'restaurant_id' => $restaurant_id);
        $result=$this->db->insert('restaurant_user', $data); 
        if($result)
        {
            $result_update=$this->db->query("UPDATE restaurant SET restaurant_like = restaurant_like + 1 WHERE id = $restaurant_id"); 
            $total_like=$this->db->query("SELECT restaurant_like FROM restaurant WHERE id = '$restaurant_id'")->row()->restaurant_like; 
            if($result_update)
                return (object)array('status' => 200, 'description' => 'Thêm like thành công','total_like'=>$total_like);
                return (object)array('status' => 201, 'description' => 'Thêm like thất bại');
        }
        return (object)array('status' => 201, 'description' => 'Thêm like thất bại');
        
    }
    
    public function hotRestaurantDb($zone,$limit,$page){
//    var_dump($zone,$limit,$stt);die;
//        in_array( $restaurantid,array('',null) )
        If($page< 1 || in_array( $limit,array('',null,'0'))|| in_array( $zone,array('',null,'0')))
        {
             return (object) array('status' => 203, 'description' => 'Tham số không đúng'); 
        }
        $stt=$limit*($page-1);
        $type_restaurant=3;
        $now=date('Y-m-d');
        //Lấy restaurant hot (lấy thêm cả tổng số like nhà hàng)
         $query="   SELECT restaurant.id,restaurant.name,restaurant.logo,restaurant.image,restaurant.hotline as image_hotline,restaurant.status,hot_price.top,count(DISTINCT e.id) as number_coupon,e.title,count(DISTINCT ru.user_id) as number_like" ."\n"
                . " FROM restaurant,restaurant_address,hot_restaurant,hot_price,ecoupon_key as ek ,ecoupon as e ,restaurant_user as ru"."\n"
                . " WHERE restaurant.id=restaurant_address.restaurant_id AND restaurant.id=ek.id_restaurant AND ek.id_ecoupon=e.id "."\n"
                . " AND restaurant.id=ru.restaurant_id "."\n"    //Thêm dòng này tỉnh tổng like
                . " AND hot_restaurant.id_restaurant=restaurant.id "."\n"
                . " AND hot_restaurant.id_price_hot = hot_price.id "."\n"
                 . "AND restaurant_address.id_zone = $zone"."\n"
                . " AND hot_price.type = $type_restaurant "
                .  "AND ( e.delete_status = 0  OR e.delete_status IS NULL)  AND restaurant.delete_status = 0   "."\n"
                . " AND time_start <= '$now'  "
                . " AND time_end >= '$now' "
                 . " GROUP BY restaurant.id"
                 . " ORDER BY hot_price.top ASC"
                ;
//        var_dump($query);die;
        $result=$this->db->query($query);
//        var_dump($result);die;
        $hot_res=$result->result_array();
        $number_hot=$result->num_rows();
        //Lấy chuỗi string_hot_id để làm điều kiện truy vấn các restaurant không hot
        foreach ($hot_res as $item)
        {
            $array_hot_id[]=$item['id'];   
        } 
        $string_hot_id='('.implode(',', $array_hot_id).')';
        if($number_hot == 0)$string_hot_id="('')";
//        var_dump($string_hot_id);die;
        if($stt == 0)
        {
            $limit = $limit - $number_hot;
            //Khởi tạo mảng hot restaurant và chuyển mảng hot_res về mảng hot restaurant
            $hot_restaurant = array(0 => '', 1 => '', 2 => '');
            foreach ($hot_res as $key => $value)
            {
                $hot_restaurant[$value['top'] - 1] = $value;
            }
            //Lấy restaurant ko hot
            
            $query = " SELECT restaurant.id,restaurant.name,restaurant.logo,restaurant.image,restaurant.hotline as image_hotline,restaurant.status,".
                "count(DISTINCT e.id) as number_coupon,".
                "SUM(amount_available)/count(amount_available) as percent,count(DISTINCT ru.user_id) as number_like " ."\n".
                "  FROM restaurant LEFT JOIN restaurant_address ON restaurant.id=restaurant_address.restaurant_id
                  LEFT JOIN ecoupon_key as ek ON restaurant.id=ek.id_restaurant
                  LEFT JOIN ecoupon as e ON ek.id_ecoupon=e.id
                  LEFT JOIN restaurant_user as ru ON restaurant.id=ru.restaurant_id 
                  WHERE restaurant_address.id_zone = $zone "."\n".
                  "AND restaurant.id NOT IN $string_hot_id "."\n".
                  "AND ( e.delete_status = 0  OR e.delete_status IS NULL)  AND restaurant.delete_status = 0   "."\n".
                  "Group by restaurant.id"."\n".    
                  "ORDER BY percent DESC,restaurant.id DESC";// LIMIT 0,$limit
            $sql_limit=" LIMIT 0,$limit ";
            //$this->db->escape();
            $restaurant = $this->db->query($query.$sql_limit)->result_array();
           
//            echo "<pre>";
//            die(print_r($restaurant));
            $total_nothot=$this->db->query($query)->num_rows();
//            var_dump($restaurant);die;
            //Tách số lượng restaurant ở đầu để đấy lên trên
            $cut_restaurant= array_slice($restaurant, 0, 3 - $number_hot);
            $rest_restaurant = array_slice($restaurant, 3 - $number_hot);
//            var_dump($rest_restaurant,$cut_restaurant);
            $array = array(100);
            //Đẩy cut_restaurant vào hot_restaurant
            for ($i = 0; $i <= 2; $i++)
            {
                for ($j = 0; $j <= 2 - $number_hot; $j++)
                {
                    if ($hot_restaurant[$i] == '' && !in_array($j,$array))
                    {     //(0 != 'abc' =>true)
                        $hot_restaurant[$i] = $cut_restaurant[$j];
//                        $only = $j;
                        $array[]=$j;
                        break;
                    }
                }
            }
            $restaurant = array_merge($hot_restaurant, $rest_restaurant);
            $total=$number_hot+$total_nothot;
//            var_dump($restaurant);die;
            foreach ($restaurant as $key => $value)
            {
                $restaurant[$key]['name']=  stripslashes(stripslashes($value['name']));
            }
            $data['restaurant']=$restaurant;
            $data['total']=$total;
            return (object)array('status' => 200, 'description' => 'Thành công','data'=>$data);
        }
        else 
        {
            $stt=$stt-$number_hot;
            $query =" SELECT restaurant.id,restaurant.name,restaurant.logo,restaurant.image,restaurant.hotline as image_hotline,restaurant.status,".
                "count(DISTINCT e.id) as number_coupon,".
                "SUM(amount_available)/count(amount_available) as percent,count(DISTINCT ru.user_id) as number_like " ."\n".
                "  FROM restaurant LEFT JOIN restaurant_address ON restaurant.id=restaurant_address.restaurant_id
                  LEFT JOIN ecoupon_key as ek ON restaurant.id=ek.id_restaurant
                  LEFT JOIN ecoupon as e ON ek.id_ecoupon=e.id
                  LEFT JOIN restaurant_user as ru ON restaurant.id=ru.restaurant_id
                  WHERE restaurant_address.id_zone = $zone "."\n".
                  "AND restaurant.id NOT IN $string_hot_id "."\n".
                  "AND ( e.delete_status = 0  OR e.delete_status IS NULL)  AND restaurant.delete_status = 0   "."\n".
                  "Group by restaurant.id"."\n".    
                  "ORDER BY percent DESC,restaurant.id DESC ";//LIMIT $stt,$limit
            
            $sql_limit=" LIMIT $stt,$limit ";
            $restaurant=$this->db->query($query.$sql_limit)->result_array();
            $total_nothot=$this->db->query($query)->num_rows();
            $total=$number_hot+$total_nothot;
            foreach ($restaurant as $key => $value)
            {
                $restaurant[$key]['name']=  stripslashes(stripslashes($value['name']));
            }
            $data['restaurant']=$restaurant;
            $data['total']=$total;
            return (object)array('status' => 200, 'description' => 'Thành công','data'=>$data);
        }  
    }   
    
    public function myRestaurantDb($zone,$limit,$page,$user_id){
//    var_dump($zone,$limit,$stt);die;
//        in_array( $restaurantid,array('',null) )
        If($page< 1 || in_array( $limit,array('',null,'0'))|| in_array( $zone,array('',null,'0')) || in_array($user_id,array('',null,'0')))
        {
             return (object) array('status' => 203, 'description' => 'Tham số không đúng'); 
        }
        $stt=$limit*($page-1);
        $type_restaurant=3;
        $now=date('Y-m-d');
        //Lấy restaurant hot 
         $query="   SELECT restaurant.id,restaurant.name,restaurant.logo,restaurant.image,restaurant.hotline as image_hotline,restaurant.status,hot_price.top,count(e.id) as number_coupon,e.title" ."\n"
                . " FROM restaurant,restaurant_user,restaurant_address,hot_restaurant,hot_price,ecoupon_key as ek ,ecoupon as e "."\n"
                . " WHERE restaurant.id=restaurant_address.restaurant_id AND restaurant.id=ek.id_restaurant AND ek.id_ecoupon=e.id "."\n"
                . " AND hot_restaurant.id_restaurant=restaurant.id "."\n"
                . " AND hot_restaurant.id_price_hot = hot_price.id "."\n"
                . " AND restaurant.id = restaurant_user.restaurant_id "."\n"
                . " AND restaurant_user.user_id = $user_id "."\n"
                 . "AND restaurant_address.id_zone = $zone"."\n"
                ."AND ( e.delete_status = 0  OR e.delete_status IS NULL)  AND restaurant.delete_status = 0   "."\n"
                . " AND hot_price.type = $type_restaurant "
                . " AND time_start <= '$now'  "
                . " AND time_end >= '$now' "
                 . " GROUP BY restaurant.id"
                 . " ORDER BY hot_price.top ASC"
                ;
//        var_dump($query);die;
        $result=$this->db->query($query);
        $hot_res=$result->result_array();
        $number_hot=$result->num_rows();
        //Lấy chuỗi string_hot_id để làm điều kiện truy vấn các restaurant không hot
        foreach ($hot_res as $item)
        {
            $array_hot_id[]=$item['id']; 
            
        } 
        $string_hot_id='('.implode(',', $array_hot_id).')';
        if($number_hot == 0)$string_hot_id="('')";
//        var_dump($string_hot_id);die;
        if($stt == 0)
        {
            $limit = $limit - $number_hot;
            //Khởi tạo mảng hot restaurant và chuyển mảng hot_res về mảng hot restaurant
            $hot_restaurant = array(0 => '', 1 => '', 2 => '');
            foreach ($hot_res as $key => $value)
            {
                $hot_restaurant[$value['top'] - 1] = $value;
            }
            //Lấy restaurant ko hot(xếp theo 
            $query = " SELECT restaurant.id,restaurant.name,restaurant.logo,restaurant.image,restaurant.hotline as image_hotline,restaurant.status,".
                 "count(DISTINCT e.id) as number_coupon,".
                "SUM(amount_available)/count(amount_available) as percent".
                "  FROM restaurant LEFT JOIN restaurant_address ON restaurant.id=restaurant_address.restaurant_id
                  LEFT JOIN ecoupon_key as ek ON restaurant.id=ek.id_restaurant
                  LEFT JOIN ecoupon as e ON ek.id_ecoupon=e.id
                  LEFT JOIN restaurant_user ON restaurant.id=restaurant_user.restaurant_id
                  WHERE restaurant_address.id_zone = $zone "."\n".
                  "AND restaurant.id NOT IN $string_hot_id "."\n".
                  "AND ( e.delete_status = 0  OR e.delete_status IS NULL)  AND restaurant.delete_status = 0   "."\n".
                  "AND restaurant_user.user_id = $user_id"."\n".
                  "Group by restaurant.id"."\n".    
                  "ORDER BY percent DESC,restaurant.id DESC";// LIMIT 0,$limit
            $sql_limit=" LIMIT 0,$limit ";
            $restaurant = $this->db->query($query.$sql_limit)->result_array();
            $total_nothot=$this->db->query($query)->num_rows();
//            var_dump($restaurant);die;
            //Tách số lượng restaurant ở đầu để đấy lên trên
            $cut_restaurant= array_slice($restaurant, 0, 3 - $number_hot);
            $rest_restaurant = array_slice($restaurant, 3 - $number_hot);
//            var_dump($rest_restaurant,$cut_restaurant);
            $array = array(100);
            //Đẩy cut_restaurant vào hot_restaurant
            for ($i = 0; $i <= 2; $i++)
            {
                for ($j = 0; $j <= 2 - $number_hot; $j++)
                {
                    if ($hot_restaurant[$i] == '' && !in_array($j,$array))
                    {     //(0 != 'abc' =>true)
                        $hot_restaurant[$i] = $cut_restaurant[$j];
//                        $only = $j;
                        $array[]=$j;
                        break;
                    }
                }
            }
            $restaurant = array_merge($hot_restaurant, $rest_restaurant);
            $total=$number_hot+$total_nothot;
            //Lấy tổng số like và thêm trường kiểm tra user đã like hay chưa
           
            foreach ($restaurant as $key => $value)
            {
                if($value == null)
                {
                    unset($restaurant[$key]);
                }
                else {
                    $restaurant[$key]['number_like']=(string)$this->db->query('SELECT id FROM restaurant_user as ru WHERE ru.restaurant_id = '.$value['id'])->num_rows();
                    //Check like 0 là chưa check 1 là check r
                    $restaurant[$key]['check_like']=(string)$this->db->query('SELECT id FROM restaurant_user as ru WHERE ru.restaurant_id = '.$value['id'].' AND user_id = '.$user_id )->num_rows();
                }
                $restaurant[$key]['name']=  stripslashes(stripslashes($value['name']));
            }
           
            $data['restaurant']=$restaurant;
            $data['total']=$total;
            return (object)array('status' => 200, 'description' => 'Thành công','data'=>$data);
        }
        else 
        {
            $stt=$stt-$number_hot;
            $query =" SELECT restaurant.id,restaurant.name,restaurant.logo,restaurant.image,restaurant.hotline as image_hotline,restaurant.status,".
                "count(DISTINCT e.id) as number_coupon,".
                "SUM(amount_available)/count(amount_available) as percent".
                "  FROM restaurant LEFT JOIN restaurant_address ON restaurant.id=restaurant_address.restaurant_id
                  LEFT JOIN ecoupon_key as ek ON restaurant.id=ek.id_restaurant
                  LEFT JOIN ecoupon as e ON ek.id_ecoupon=e.id
                  LEFT JOIN restaurant_user ON restaurant.id=restaurant_user.restaurant_id
                  WHERE restaurant_address.id_zone = $zone "."\n".
                  "AND restaurant.id NOT IN $string_hot_id "."\n".
                  "AND ( e.delete_status = 0  OR e.delete_status IS NULL)  AND restaurant.delete_status = 0   "."\n".
                  "AND restaurant_user.user_id = $user_id"."\n".
                  "Group by restaurant.id"."\n".    
                  "ORDER BY percent DESC,restaurant.id DESC ";//LIMIT $stt,$limit
                
            $sql_limit=" LIMIT $stt,$limit ";
            $restaurant=$this->db->query($query.$sql_limit)->result_array();
            $total_nothot=$this->db->query($query)->num_rows();
            $total=$number_hot+$total_nothot;
             
           //Lấy tổng số like và thêm trường kiểm tra user đã like hay chưa
            foreach ($restaurant as $key => $value)
            {
                $restaurant[$key]['number_like']=(string)$this->db->query('SELECT id FROM restaurant_user as ru WHERE ru.restaurant_id = '.$value['id'])->num_rows();
                //Check like 0 là chưa check 1 là check r
                $restaurant[$key]['check_like']=(string)$this->db->query('SELECT id FROM restaurant_user as ru WHERE ru.restaurant_id = '.$value['id'].' AND user_id = '.$user_id )->num_rows();
            }
            foreach ($restaurant as $key => $value)
            {
                $restaurant[$key]['name']=  stripslashes(stripslashes($value['name']));
            }
            $data['restaurant']=$restaurant;
            $data['total']=$total;
            return (object)array('status' => 200, 'description' => 'Thành công','data'=>$data);
        }  
    }   
    
    
    public function getAppDb()
    {
        $data=$this->db->query("SELECT * FROM  wicity_app ");
        $app=$data->result_array();
        return (object)array('status' => 200, 'description' => 'Thành công','app'=>$app);
    }
    
    
    public function getTermDb()
    {
        $company=$this->db->query("SELECT content FROM  options WHERE tags='company'")->row()->content;
        $version=$this->db->query("SELECT content FROM  options WHERE tags='version'")->row()->content;
        $term=$this->db->query("SELECT content FROM  options WHERE tags='term'")->row()->content;
        $logo=$this->db->query("SELECT content FROM  options WHERE tags='logo_gpeople'")->row()->content;
        $data=array('company'=>$company,'term'=>$term,'version'=>$version,'logo'=>$logo);
        return (object)array('status' => 200, 'description' => 'Thành công','data'=>$data);
    }
    
    public function getStatic()
    {
        $distance=$this->db->query("SELECT content FROM  options WHERE tags='distance'")->row()->content;
        $mindistance_push=$this->db->query("SELECT content FROM  options WHERE tags='mindistance_push'")->row()->content;
        $time_push=$this->db->query("SELECT content FROM  options WHERE tags='time_push'")->row()->content;
        $version=$this->db->query("SELECT content FROM  options WHERE tags='version'")->row()->content;
        $link_down_app=$this->db->query("SELECT content FROM  options WHERE tags='link_down_app'")->row()->content;
        $sms_getpass=$this->db->query("SELECT content FROM  options WHERE tags='sms_getpass'")->row()->content;
        $fanpage=$this->db->query("SELECT content FROM  options WHERE tags='fanpage'")->row()->content;
        $share_coupon=$this->db->query("SELECT content FROM  options WHERE tags='share_coupon'")->row()->content;
        $share_incen=$this->db->query("SELECT content FROM  options WHERE tags='share_incen'")->row()->content;
        $introduce=$this->db->query("SELECT content FROM  options WHERE tags='introduce'")->row()->content;
        $data=array('distance'=>$distance,'mindistance_push'=>$mindistance_push,'time_push'=>$time_push,'version'=>$version,'link_down_app'=>$link_down_app,'sms_getpass'=>$sms_getpass,'fanpage'=>$fanpage,'share_coupon'=>$share_coupon,'share_incen'=>$share_incen,'introduce'=>$introduce);
        return (object)array('status' => 200, 'description' => 'Thành công','data'=>$data);
    }
    public function getQuestionDb()
    {
        $data=$this->db->query("SELECT * FROM  faq ");
        $app=$data->result_array();
        foreach($app as $key => $value)
        {
            $app[$key]['answer']=str_replace(array("<br />","<br >","<br/>","<br>"), "\n", $value['answer']);
        }
        return (object)array('status' => 200, 'description' => 'Thành công','question'=>$app);
    }
    
    public function listZoneDB()
    {
        $data=$this->db->query("SELECT id,title FROM zone ");
        $zone=$data->result_array();
        return (object)array('status' => 200, 'description' => 'Thành công','data'=>$zone);
    }
    
   
//     public function getKeyDb($user_id,$key,$type)
//    {
//        if($type == 1){
//            $key_type = 'key_ios';    
//        }else if($type == 2){
//            $key_type = 'key_android';
//        }else if($type == 3){
//            $key_type = 'key_winphone';
//        }
//        
//        $data = array(
//            $key_type => $key
//        );
//        
//        if( !in_array($user_id, array(null, '')) && $user_id != 0 )
//        {
//            $data['user_id'] = $user_id;
//        }
//        
//        $count_x = $this->db->query("SELECT user_id FROM `push_key` WHERE ".$key_type." = '".$key."' AND user_id = '".$user_id."'")->num_rows();
//        if($count_x > 0){
//            return 201;
//        }
//        
//        $count = $this->db->query("SELECT * FROM `push_key` WHERE ".$key_type." = '".$key."'")->num_rows();
//        $count_user = $this->db->query("SELECT user_id FROM `push_key` WHERE user_id = ".$user_id)->num_rows();
//        if($count > 0){ //key đã tồn tại
//            $this->db->query("DELETE FROM push_key WHERE ".$key_type." = '".$key."'");
//            if($count_user > 0){ //user đã tồn tại
//                $this->db->delete('push_key', "user_id = ".$user_id);
//                $this->db->insert('push_key', $data);    
//            }else{
//                $this->db->insert('push_key', $data);
//            }
//        }else{
//            if($count_user > 0){ //user đã tồn tại
//                $this->db->delete('push_key', "user_id = ".$user_id);
//                $this->db->insert('push_key', $data);    
//            }else{
//                $this->db->insert('push_key', $data);
//            }
//        }
//        return 200;
//    }
    
    //1 user mà nhiều key thì inset hàng mới,1 key mà nhiều user thì inset hàng mới,1 key mà ko co user(trong db co user ,có key đó thì inset thêm trường đó để user là 0 hay null j đó)
//    public function getKeyDb($user_id,$key,$type)
//    {
//        //CHeck type
//        if($type == 1){
//            $key_type = 'key_ios';    
//        }else if($type == 2){
//            $key_type = 'key_android';
//        }else if($type == 3){
//            $key_type = 'key_winphone';
//        } 
//        //Nếu gửi lên có user_id
//        if( !in_array($user_id, array(null, '')) && $user_id != 0 )
//        {
//            //Kiểm tra xem có hàng nào có user id và key ko
//            $count_x = $this->db->query("SELECT user_id FROM `push_key` WHERE " . $key_type . " = '" . $key . "' AND user_id = '" . $user_id . "'")->num_rows();
//            //Nếu có rồi thì thôi không làm gì nữa
//            if ($count_x > 0)
//            {
//                return 201;
//            }            
//            //Nếu chưa có thì kiểm tra xem có hàng nào có user id và key đó là null không
//            $dataCheck=$this->db->query("SELECT id FROM `push_key` WHERE " . $key_type . " IS NULL " . " AND user_id = '" . $user_id . "'");
//            $countKeyNull = $dataCheck ->num_rows();
//            //Nếu có thì update vào hàng có key null đó,neU khONG thì insert dòng mới.
//            if ($countKeyNull > 0)
//            {
//                $this->db->update('push_key', array($key_type => $key), array('id' => $dataCheck->row()->id));
//            } else
//            {
////                //KIểm tra xem hàng nào có user id là null và chứa key đó không.
////                $dataCheck=$this->db->query("SELECT id FROM `push_key` WHERE  " . $key_type . " = '" . $key . "'  AND user_id IS NULL '");
////                //Nếu có thì update user_id vào dòng đó,không có thì insert
////                $countUserNull = $dataCheck ->num_rows();
////                if ($countUserNull > 0)
////                {
////                    $this->db->update('push_key', array(user_id => $user_id), array('id' => $dataCheck->row()->id));
////                    return 200;
////                }
//                $this->db->insert('push_key', array($key_type => $key, 'user_id' => $user_id));
//            }
//        }
//        //Nếu gửi lên ko có user_id thì kiểm tra có token key va user_id null chưa,có rồi thì ko làm j nữa,chưa có thì insert key.
//        else {
//           $count_k=$this->db->query("SELECT user_id FROM `push_key` WHERE ".$key_type." = '".$key."'"." AND user_id IS NULL ")->num_rows(); 
//           if($count_k >0) return 201;
//           $this->db->insert('push_key',array($key_type => $key));
//           return 200;
//        }
//    }
    public function getKeyDb($user_id,$key,$type)
    {
        //CHeck type
        if($type == 1){
            $key_type = 'key_ios';    
        }else if($type == 2){
            $key_type = 'key_android';
        }else if($type == 3){
            $key_type = 'key_winphone';
        } 
        //Nếu gửi lên không có user_id,kiểm tra tồn tại key không,tồn tại thì update trường user chuyển thành null,ko tồn tại thì insert
        if( in_array($user_id, array(null, '')) || $user_id == 0 )
        {
            //Kiểm tra xem có hàng nào có user id và key ko
            $countKey= $this->db->query("SELECT id FROM $key_type WHERE key_app = '$key'");
            //Nếu có rồi thì update user là null
            if ($countKey->num_rows() > 0)
            {
                $this->db->update($key_type, array('user_id' => null), array('id' => $countKey->row()->id));
                return (object)array('status' => 200, 'description' => 'Update user null đối với key này');
            }     
            if(strlen($key) < 10)  //key chuân là 64 kí tự nhưng có thể thay đổi,chỉ bắt >30 thôi.
            {
                return (object)array('status' => 201, 'description' => 'Key không hợp lệ');
            }    
            $this->db->insert($key_type, array('key_app' => $key));
            return (object)array('status' => 200, 'description' => 'Insert key mới thành công');
        }
        //Nếu gửi lên có user_id thì check key ko có báo lỗi,key có update trường user vào hàng có key đó. 
        else {
           $checkUser= $this->db->query("SELECT id FROM member WHERE id= '$user_id'");
           if($checkUser->num_rows() == 0)return (object)array('status' => 201, 'description' => 'User này không tồn tại');
           $checkKey= $this->db->query("SELECT id FROM $key_type WHERE key_app = '$key'");
           if($checkKey->num_rows() == 0)return (object)array('status' => 201, 'description' => 'Key này không tồn tại');
           $this->db->update($key_type, array('user_id' => $user_id), array('id' => $checkKey->row()->id));
           return (object)array('status' => 200, 'description' => 'Fix lại trường user trên key này thành công');
        }
    }
    
//     public function setAppDb($key,$user_id,$type,$getNotice,$numberNotice) //vẫn còn 2 tham số rung và âm báo
//    {
//        $arrayUpdate=array('number_notice'=>$numberNotice,'status_get_notice'=>$getNotice);
//        //Nếu có user_id thì lưu hết tất cả trạng thái vào trong bảng user
//        if(!in_array($user_id,array('',null,0)))
//        {
//            //Check xem user đó có tồn tại không
//            $checkUser=$this->db->query("SELECT * FROM member WHERE id = '$user_id'");
//            $numberRow=$checkUser->num_rows();
//            if($numberRow == 0)return (object)array('status' => 201,'description'=>'Không thấy User'); 
//            $this->db->update('member',$arrayUpdate,array('id'=>$checkUser->row()->id));   
//            return (object)array('status' => 200,'description'=>'Thành công');    
//        }
//        //Nếu không có user_id thì lưu vào bảng push_key
//        //Check xem có key đó không để lưu
//        //CHeck type
//        if($type == 1){
//            $key_type = 'key_ios';    
//        }else if($type == 2){
//            $key_type = 'key_android';
//        }else if($type == 3){
//            $key_type = 'key_winphone';
//        } 
//        $checkKey=$this->db->query("SELECT id FROM `push_key` WHERE " . $key_type . " = '" . $key ."'" . " AND user_id IS NULL ");
//        if($checkKey->num_rows() == 0)return (object)array('status' => 201,'description'=>'Không thấy key.'); 
//        $this->db->update('push_key', $arrayUpdate,array('id'=>$checkKey->row()->id));
//        return (object)array('status' => 200,'description'=>'Thành công'); 
//    }
    
    public function setAppDb($key,$user_id,$type,$getNotice,$numberNotice,$before) //vẫn còn 2 tham số rung và âm báo
    {
        //Lọc kiểu
        if($type == 1){
            $key_type = 'key_ios';    
        }else if($type == 2){
            $key_type = 'key_android';
        }else if($type == 3){
            $key_type = 'key_winphone';
        } 
        //Mảng update
        $arrayUpdate=array('number_notice'=>$numberNotice,'status_get_notice'=>$getNotice,'number_notice_used'=>0,'date_notice'=>date('Y-m-d'));
        //Nếu không có user_id thì update vào bảng key
        if(in_array($user_id,array('',null,0)))
        {
            //Check xem key đó có tồn tại không
            $checkKey=$this->db->query("SELECT id FROM $key_type WHERE key_app = '$key'");
            $numberRow=$checkKey->num_rows();
            if($numberRow == 0)return (object)array('status' => 201,'description'=>'Truyền lên ko có user,ko tìm thấy key');
             $checkOther=$this->db->query("SELECT * FROM $key_type WHERE key_app = '$key' AND user_id IS NOT NULL");
           if($checkOther->num_rows() != 0)return (object)array('status' => 201,'description'=>'Truyền lên ko có user,key này đã có user sử dụng ,phải truyền cả user');
            $arrayUpdate=array('number_notice'=>$numberNotice,'status_get_notice'=>$getNotice,'number_notice_used'=>0,'date_notice'=>date('Y-m-d'),'user_id'=>null);
            $this->db->update($key_type,$arrayUpdate,array('id'=>$checkKey->row()->id));   
            return (object)array('status' => 200,'description'=>'Truyền lên ko có user,Update trạng thái key thành công');    
        }
        //Nếu có thì update vào bảng user
        $checkUser=$this->db->query("SELECT id FROM member WHERE id = '$user_id'");
        if($checkUser->num_rows() == 0)return (object)array('status' => 201,'description'=>'Truyền lên có user,Không thấy user.'); 
        //Check xem user này có đang sử dụng key đó không
        $check=$this->db->query("SELECT id FROM $key_type WHERE user_id = '$user_id' AND key_app = '$key'");
        if($check->num_rows() == 0)return (object)array('status' => 201,'description'=>'Truyền lên có user,User này không khớp với key(dang ko su dung key nay)'); 
        $arrayUpdate=array('number_notice'=>$numberNotice,'status_get_notice'=>$getNotice,'number_notice_used'=>0,'date_notice'=>date('Y-m-d'),'before_notice'=>$before);
        $this->db->update('member', $arrayUpdate,array('id'=>$checkUser->row()->id));
        return (object)array('status' => 200,'description'=>'Truyền lên có user,update trên user thành công'); 
        
    }
    
    public function getSetAppDb($key,$user_id,$type) //vẫn còn 2 tham số rung và âm báo
    {
        //Lọc kiểu
        if($type == 1){
            $key_type = 'key_ios';    
        }else if($type == 2){
            $key_type = 'key_android';
        }else if($type == 3){
            $key_type = 'key_winphone';
        } 
        //Nếu không có user_id thì update vào bảng key
        if(in_array($user_id,array('',null,0)))
        {
            //Check xem key đó có tồn tại không
            $checkKey=$this->db->query("SELECT number_notice,status_get_notice FROM $key_type WHERE key_app = '$key'");
            $numberRow=$checkKey->num_rows();
            if($numberRow == 0)return (object)array('status' => 201,'description'=>'Truyền lên ko có user,ko tìm thấy key');
            //check xem key đã được sử dụng chưa
           $checkOther=$this->db->query("SELECT * FROM $key_type WHERE key_app = '$key' AND user_id IS NOT NULL");
           if($checkOther->num_rows() != 0)return (object)array('status' => 201,'description'=>'Truyền lên ko có user,key này đã có user sử dụng ,phải truyền cả user');
            $data=$checkKey->row();
            return (object)array('status' => 200,'description'=>'Truyền lên ko có user,tìm thấy key','data'=>$data);    
        }
        $checkUser=$this->db->query("SELECT number_notice,status_get_notice,before_notice FROM member WHERE id = '$user_id'");
        if($checkUser->num_rows() == 0)return (object)array('status' => 201,'description'=>'Truyền lên có user,Không thấy user.'); 
        //Check xem user này có đang sử dụng key đó không
        $check=$this->db->query("SELECT id FROM $key_type WHERE user_id = '$user_id' AND key_app = '$key'");
        if($check->num_rows() == 0)return (object)array('status' => 201,'description'=>'Truyền lên có user,User này không khớp với key(dang ko su dung key nay)'); 
        $data=$checkUser->row();
        return (object)array('status' => 200,'description'=>'Truyền lên có user,tìm thấy key','data'=>$data);      
    }
    
    /**
     * Get Slide coupon with zone .
     * 
     * @param int $zone
     * @return object
     */
    public function getSlideCouponDb($zone)
    {
//        $timeupdate = $this->db->query("SELECT content FROM options WHERE tags = 'time_update_api_static'")->row_object();
//        var_dump($timeupdate->content);die;
        $checkZone=$this->db->query("SELECT id FROM zone WHERE id = $zone")->num_rows;
        $default[]=array('id'=>1,'url'=>'google.com.vn','image'=>'images/slides/8412ef8cb970c688a9d887d845a56229.jpg');
        $default[]=array('id'=>2,'url'=>'24.com.vn','image'=>'images/slides/028ccc9a63febdcbcf451a41c086eb8a.jpg');
        if($checkZone==0){
            return (object)array('status' => 202,'description'=>'Không thấy zone','default_image'=>$this->default);//Không tìm thấy zone
        }
        
//        if($time < $timeupdate->content)
//        {
            $slides = $this->db->query("SELECT slidecoupon.* FROM slidecoupon,slidecoupon_zone Where slidecoupon.id=slidecoupon_zone.slide_id AND slidecoupon_zone.zone_id = $zone")->result_array();
            if(count($slides)==0) 
            {
               return (object)array('status' => 201,'description'=>'Không thấy slide','default_image'=>$this->default);  //với zone đã tìm ko tim thay slide
            }
            $arr = array(
                  'slides' => $slides,
            );
            return (object)array('status' => 200,'description'=>'Tìm thấy slide', 'data' => (object)$arr);   //tìm thấy slie 
//        }else{
//            return (object)array('status' => 202, 'data' => '');
//        }
    }
    
    /**
     * Get Slide restaurant with zone .
     * 
     * @param int $zone
     * @return object
     */
    public function getSlideRestaurantDb($zone)
    {
//        $timeupdate = $this->db->query("SELECT content FROM options WHERE tags = 'time_update_api_static'")->row_object();
//        var_dump($timeupdate->content);die;
        $checkZone=$this->db->query("SELECT id FROM zone WHERE id = $zone")->num_rows;
        $default[]=array('id'=>1,'url'=>'google.com.vn','image'=>'images/slides/8412ef8cb970c688a9d887d845a56229.jpg');
        $default[]=array('id'=>2,'url'=>'24.com.vn','image'=>'images/slides/028ccc9a63febdcbcf451a41c086eb8a.jpg');
        if($checkZone==0){
            return (object)array('status' => 202,'description'=>'Không thấy zone','default_image'=>$this->default);//Không tìm thấy zone
        }
        
//        if($time < $timeupdate->content)
//        {
            $slides = $this->db->query("SELECT sliderestaurant.* FROM sliderestaurant,sliderestaurant_zone Where sliderestaurant.id=sliderestaurant_zone.slide_id AND sliderestaurant_zone.zone_id = $zone")->result_array();
            if(count($slides)==0) 
            {
               return (object)array('status' => 201,'description'=>'Không thấy slide','default_image'=>$this->default);  //với zone đã tìm ko tim thay slide
            }
            $arr = array(
                  'slides' => $slides,
            );
            return (object)array('status' => 200,'description'=>'Tìm thấy slide', 'data' => (object)$arr);   //tìm thấy slie 
//        }else{
//            return (object)array('status' => 202, 'data' => '');
//        }
    }
    
    public function pushByTokenDb($message, $key, $type)
    {
        if($type == 1) //ios
        {
            $this->push_ios($message,array($key));
            return array('status' => 200, 'description' => 'Push thành công iOS');
        }elseif($type == 2){ //android
            $result=$this->send_push_notification(array($key),$message);
            return array('description' => $result);
        }
    }
    
    private function push_ios($notification, $arr_ios)
    {
        $TEXT_ALERT = $notification;
        $BADGE = 1;
        $SOUND = 'default';
        $SERVER_ID = '123';
        $NAME = 'name';
        $SANBOX = 1;
//e1edea3201896340c0a3ee204159dab77e52107b86671c35158600b88e217562
        $token1 = '0fb43f74cebe8e867f9c9aeafba649138750bc82e7a20f19b3eadc82ab7a95b7';
        $token2 = 'd4383f76343a311252a60247980e9f4c76fd411c5f79287e4202a9b31d0778d4';
        $deviceTokenList = $arr_ios;

        $payload = array();
        $payload['aps'] = array('alert' => $TEXT_ALERT, 'badge' => $BADGE, 'sound' => $SOUND);

        $payload['server'] = array('serverId' => $SERVER_ID, 'name' => $NAME);

        $payload = json_encode($payload);


        if ($SANBOX)
        {
            $apnsHost = 'gateway.sandbox.push.apple.com';
        } else
        {
            $apnsHost = 'gateway.push.apple.com';
        }
        $apnsPort = 2195;
        $apnsCert = 'push_development.pem';


//make connection
        $streamContext = stream_context_create();
        stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
        $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);

        if ($apns == NULL || $error != NULL)
        {
            echo "Error when connect to " . $apnsPort . ', err string ' . $errorString;
            die;
        }

//        echo "connect success\n";
        foreach ($deviceTokenList as $deviceToken)
        {
//            echo "Add token $deviceToken\n";
            //build message
            $apnsMessage = chr(0) . chr(0) . chr(32)
                    . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
            fwrite($apns, $apnsMessage);
        }

//close connection
        @socket_close($apns);
        fclose($apns);

//        echo "Send success \n";


        return 200;
    }

    private function send_push_notification($registation_ids, $message)
    {
        //die(GOOGLE_API_KEY);
        //die('d');
        $url = 'https://android.googleapis.com/gcm/send';

        $fields = array(
            'registration_ids' => $registation_ids,
            'data' => array('price' => $message),
        );
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        //print_r($headers);
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE)
        {
            //die('Curl failed: ' . curl_error($ch));
            return 201;
        }

        // Close connection
        curl_close($ch);
        return $result;
//        return 200;
    }
    
    public function syncaddcoupon($arr_codecoupon, $data_coupon, $wicard_id_user){
		$rdata = $this->db->query('SELECT id FROM restaurant WHERE manage_id = '.$wicard_id_user.' ');
		if( $rdata->num_rows() == 0 ){
			return array('status' => 201, 'content' => 'tài khoản này chưa quản lý nhà hàng nào');
		}
		$id_restaurant = $rdata->row_object()->id;
		$zdata = $this->db->query('SELECT DISTINCT(id_zone) FROM restaurant_address WHERE restaurant_id = '.$id_restaurant.' ')->result_object();
		
		// add ecoupon
		$this->db->insert('ecoupon', $data_coupon);
        $id = $this->db->insert_id(); 
		// add ecoupon user
			
		for( $i = 0; $i< count($arr_codecoupon);$i++ ){
			$this->db->insert('ecoupon_user', array('coupon_id' => $id, 'active' => 0, 'code_coupon' =>  $arr_codecoupon[$i] , 'admin_id' => $wicard_id_user, 'is_wicity' => 1));
		}
		
		//
		$c_cate = array('id_restaurant' => $id_restaurant, 'id_ecoupon' => $id, 'admin_id' => $wicard_id_user, 'created' => date('Y-m-d H:i:s'));
        $this->db->insert('ecoupon_key', $c_cate);
			
		foreach ($zdata as $el => $le){
			$k_cate = array('id_coupon' => $id, 'id_zone' => $le->id_zone, 'admin_id' => $wicard_id_user, 'created' => date('Y-m-d H:i:s'));
			$this->db->insert('ecoupon_zone_key', $k_cate);
		}
		die('200');
	}
     
}